package com.shiwaixiangcun.customer.module.homeservice

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.AddressBean
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil
import com.shiwaixiangcun.customer.module.homeservice.bean.PickerViewData
import com.shiwaixiangcun.customer.module.homeservice.bean.TimeBean
import com.shiwaixiangcun.customer.module.mall.ManageAddressActivity
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.dialog.DialogStatus
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.DateUtil
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.xujhin.pickerview.OptionsPickerView
import com.xujhin.pickerview.model.IPickerViewData
import kotlinx.android.synthetic.main.activity_appointment.*
import kotlinx.android.synthetic.main.top_bar_white.*
import java.text.Format
import java.text.SimpleDateFormat
import java.util.*

/**
 * 预约服务页面
 */
class AppointmentActivity : BaseActivity(), View.OnClickListener {
    private val CHOOSE_ADDRESS = 0x1001
    private var addressId: Int? = null
    private var userName: String? = null
    private var userPhone: String? = null
    private var userAddress: String? = null

    //widget
    private var mTvAddressName: TextView? = null
    private var mTvAddressPhone: TextView? = null
    private var mTvAddressAddress: TextView? = null
    private var addressView: View? = null
    private var addressEmptyView: View? = null


    private var serviceTime: String? = null
    private var tokenString: String? = null
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
            R.id.rlayout_time -> {
                showDateDialog()

            }
            R.id.llayout_address -> {
                val bundle = Bundle()
                bundle.putBoolean("clickable", true)
                readyGoForResult(ManageAddressActivity::class.java, CHOOSE_ADDRESS, bundle)
            }
            R.id.btn_input -> {


                when {
                    serviceTime == null -> showToastShort("请选择上门服务时间")
                    addressId == 0 -> showToastShort("请确认地址")
                    else -> commitData()
                }


            }
        }
    }


    /**
     * 显示时间选择对话框
     */
    private fun showDateDialog() {
        val pvOptions = OptionsPickerView<TimeBean, String, IPickerViewData>(mContext)
        val options1Items = ArrayList<TimeBean>()
        val options2Items = ArrayList<ArrayList<String>>()
        val options3Items = ArrayList<ArrayList<ArrayList<IPickerViewData>>>()
        options1Items.add(TimeBean("今天"))
        (1..5).mapTo(options1Items) { TimeBean(getDateAfter(it)) }
        for (i in 0..options1Items.size) {
            when (i) {
                0 -> {
                    //选项 1 2
                    val options3Items_02: ArrayList<ArrayList<IPickerViewData>> = getmD2()
                    var options2Items_01 = ArrayList<String>()
                    options2Items_01 = getTodayHourData()

                    options2Items.add(options2Items_01)
                    options3Items.add(options3Items_02)
                }
                else -> {
                    //选项 1 2
                    var options2Items_01 = ArrayList<String>()
                    var options3Items_03 = ArrayList<ArrayList<IPickerViewData>>()
                    options2Items_01 = getHourData()
                    options3Items_03 = getmD()
                    options2Items.add(options2Items_01)
                    options3Items.add(options3Items_03)
                }
            }
        }

        //三级联动效果
        pvOptions.setPicker(options1Items, options2Items, options3Items, true)
        pvOptions.setTitle(" ")
        pvOptions.setCyclic(false, false, false)
        //设置默认选中的三级项目
        //监听确定选择按钮
        pvOptions.setSelectOptions(0, 0, 0)
        pvOptions.setOnoptionsSelectListener(OptionsPickerView.OnOptionsSelectListener { options1, option2, options3 ->
            val result = "${options1Items[options1].pickerViewText} " +
                    options2Items[options1][option2].dropLast(1) +
                    ":${options3Items[options1][option2][options3].pickerViewText.dropLast(1)}"


            var resultDay: String? = null
            var timeDay: String? = null
            var timeHour: String? = null
            var timeMinutes: String? = null
            timeDay = options1Items[options1].pickerViewText
            timeHour = options2Items[options1][option2].dropLast(1)
            timeMinutes = options3Items[options1][option2][options3].pickerViewText.dropLast(1)
            resultDay = when {
                timeDay == "今天" -> DateUtil.getToday()
                timeDay.length < 9 -> {
                    val day = Date()
                    val df = SimpleDateFormat("yyyy")
                    "${df.format(day)}-${options1Items[options1].pickerViewText}"
                }
                else -> timeDay
            }
            serviceTime = "$resultDay $timeHour:$timeMinutes"
            tv_service_time.text = result

            Log.e(BUG_TAG, result)
            Log.e(BUG_TAG, serviceTime)

        })
        //点击弹出选项选择器
        pvOptions.show()
    }

    /**
     * today Hour
     */
    private fun getTodayHourData(): ArrayList<String> {
        var max = currentHour()
        if (max < 23 && currentMin() > 45) {
            max += 1
        }
        return (max..23).mapTo(ArrayList()) {

            if (it < 10) {
                "0" + it.toString() + "点"
            } else {
                it.toString() + "点"
            }
        }
    }

    /**
     * 明天 后天 点
     */
    private fun getHourData(): ArrayList<String> {
        val lists = ArrayList<String>()
        for (i in 0..23) {

            if (i >= 10) {
                lists.add(i.toString() + "点")
            } else {
                lists.add("0" + i.toString() + "点")
            }
        }
        return lists
    }


    /**
     * 明天 后天
     */
    private fun getmD(): ArrayList<ArrayList<IPickerViewData>> {
        val d = ArrayList<ArrayList<IPickerViewData>>()
        for (i in 0..23) {
            d.add(getMinData())
        }
        return d
    }

    /**
     * 明天 后天  2222
     */
    private fun getmD2(): ArrayList<ArrayList<IPickerViewData>> {
        //14
        var max = currentHour()
        if (currentMin() > 45) {
            max += 1
        }
        val value = 24 - max
        val d = ArrayList<ArrayList<IPickerViewData>>()
        for (i in 0 until value) {
            if (i == 0) {
                d.add(getTodayMinData())
            } else {
                d.add(getMinData())
            }

        }
        return d
    }


    /**
     * 获取当天分钟(只能选取当前时间以后的分钟数）
     */
    private fun getTodayMinData(): ArrayList<IPickerViewData> {
        val dataArrayList = ArrayList<IPickerViewData>()
        val min = currentMin()
        val pos = 60 / min
        for (i in pos..5) {

            if (i == 0) {
                dataArrayList.add(PickerViewData("00分"))
            } else {
                dataArrayList.add(PickerViewData((i * 10).toString() + "分"))
            }
        }
        return dataArrayList
    }


    /**
     * 获取不是当天的分钟数（0-16）
     */
    private fun getMinData(): ArrayList<IPickerViewData> {
        val dataArrayList = ArrayList<IPickerViewData>()
        for (i in 0..5) {
            if (i == 0) {
                dataArrayList.add(PickerViewData("00分"))
            } else {
                dataArrayList.add(PickerViewData((i * 10).toString() + "分"))
            }
        }
        return dataArrayList
    }


    /**
     * 得到几天后的时间
     * @param day
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    private fun getDateAfter(day: Int): String {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + day)
        val today = calendar.time
        var format: Format? = null
        format = if (DateUtil.isThisYear(today)) {
            SimpleDateFormat("MM-dd")
        } else {
            SimpleDateFormat("yyyy-MM-dd")
        }
        return format.format(today)
    }

    /**
     *获取当前分钟数
     */
    private fun currentMin(): Int {
        val cal = Calendar.getInstance()
        return cal.get(Calendar.MINUTE)
    }

    private fun currentHour(): Int {
        val cal = Calendar.getInstance()
        return cal.get(Calendar.HOUR_OF_DAY)
    }

    /**
     * 提交预约
     */
    private fun commitData() {
        serviceID?.let {
            addressId?.let { it1 ->
                OkGo.post<String>(GlobalApi.commitAppointment)
                        .params("access_token", tokenString)
                        .params("addressId", it1)
                        .params("id", it)
                        .params("serviceDate", serviceTime)
                        .params("remark", edt_others.text.toString())
                        .execute(object : StringCallback() {
                            override fun onSuccess(response: Response<String>?) {
                                val type = object : TypeToken<CommonObjCallBack<Any>>() {}.type
                                val fromJson = JsonUtil.fromJson<CommonObjCallBack<Any>>(response?.body(), type)
                                when (fromJson.responseCode) {
                                    ResponseConfig.SUCCESS -> {
                                        val dialogStatus = DialogStatus(mContext)
                                        dialogStatus.setDialogTitle("预约成功")
                                        dialogStatus.setDialogInfo("请耐心等待，保持电话畅通。\n" +
                                                "服务人员会尽快与您联系。")
                                        dialogStatus.listener = object : DialogStatus.onCallBackListener {
                                            override fun closeBtn(dialog: DialogStatus) {
                                                dialog.dismiss()
                                                finish()
                                            }

                                            override fun confirmBtn(dialog: DialogStatus) {
                                                dialog.dismiss()
                                                finish()

                                            }
                                        }
                                        dialogStatus.show()
                                    }
                                    else -> {
                                        showToastShort(fromJson.message)
                                    }
                                }
                            }
                        })
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CHOOSE_ADDRESS && resultCode == 0x1010) {
            Log.e(BUG_TAG, "选择地址返回")

            val chooseBundle = data?.extras
            if (chooseBundle?.isEmpty!!) {
                return
            } else {
                addressId = chooseBundle.getInt("addressID", 0)
                userName = chooseBundle.getString("userName")
                userPhone = chooseBundle.getString("userPhone")
                userAddress = chooseBundle.getString("userAddress")
                llayout_address.removeAllViews()
                llayout_address.addView(addressView)
                mTvAddressPhone?.text = userPhone
                mTvAddressName?.text = userName
                mTvAddressAddress?.text = userAddress
            }

        }


    }

    /**
     * 获取用户默认地址
     */
    private fun initDefaultAddress() {

        OkGo.get<String>(GlobalApi.getAddress)
                .params("access_token", tokenString)
                .params("fields", "")
                .execute(object : StringCallback() {

                    override fun onError(response: Response<String>?) {
                        llayout_address.removeAllViews()
                        llayout_address.addView(addressEmptyView)
                    }

                    override fun onSuccess(response: Response<String>?) {

                        Log.e(BUG_TAG, "onSuccess")
                        if (response == null) {
                            return
                        }
                        Log.e(BUG_TAG, response.toString())
                        val listType = object : TypeToken<ResponseEntity<List<AddressBean>>>() {}.type
                        val entity = Gson().fromJson<ResponseEntity<List<AddressBean>>>(response.body(), listType) ?: return
                        when (entity.responseCode) {
                            1001 -> if (entity.data.isNotEmpty()) {
                                val defaultAddress = entity.data[0]
                                llayout_address.removeAllViews()
                                llayout_address.addView(addressView)
                                addressId = defaultAddress.id
                                userName = defaultAddress.deliveryName
                                userPhone = defaultAddress.deliveryPhone
                                userAddress = defaultAddress.deliveryAddress
                                mTvAddressPhone?.text = userPhone
                                mTvAddressName?.text = userName
                                mTvAddressAddress?.text = userAddress
                            } else {
                                llayout_address.removeAllViews()
                                llayout_address.addView(addressEmptyView)
                            }
                            else -> {
                                llayout_address.removeAllViews()
                                llayout_address.addView(addressEmptyView)
                            }
                        }
                    }


                })
    }

    override fun onResume() {
        super.onResume()
        scrollView.smoothScrollTo(0, 20)
    }

    private var serviceID: Long? = null
    private var serviceName: String? = null
    private var servicePic: String? = null
    private var serviceDesc: String? = null
    private var servicePrice: String? = null
    var strToken: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_appointment)
        initBundleData()
        initViewAndEvent()
        initDefaultAddress()
    }

    private fun initBundleData() {

        serviceID = intent.extras.getLong("id")
        serviceName = intent.extras.getString("name")
        servicePic = intent.extras.getString("pic")
        serviceDesc = intent.extras.getString("desc")
        servicePrice = intent.extras.getString("price")

        ImageDisplayUtil.showImageView(mContext, servicePic, iv_house_cover)
        tv_house_title.text = serviceName
        tv_house_desc.text = serviceDesc
        tv_price.text = servicePrice

    }

    /**
     * 初始化试图以及点击事件
     */
    private fun initViewAndEvent() {
        tv_page_name.text = "预约服务"
        tokenString = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        addressView = layoutInflater.inflate(R.layout.layout_address, null, false)
        addressEmptyView = layoutInflater.inflate(R.layout.layout_address_empty, null, false)
        mTvAddressAddress = addressView?.findViewById(R.id.tv_address)
        mTvAddressName = addressView?.findViewById(R.id.tv_user_name)
        mTvAddressPhone = addressView?.findViewById(R.id.tv_user_phone)
        back_left.setOnClickListener(this)
        rlayout_time.setOnClickListener(this)
        llayout_address.setOnClickListener(this)
        btn_input.setOnClickListener(this)


    }
}
